package com.csii.adhoc.controller.dbLink;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csii.adhoc.annotation.OperationLog;
import com.csii.adhoc.dblink.service.DbLinkService;
import com.csii.adhoc.dblink.DbLinkPo;
import com.csii.adhoc.dblink.DbLinkVo;
import com.csii.adhoc.util.DateUtils;
import com.csii.result.APIResult;
import com.csii.result.PageVo;
//import com.github.pagehelper.Page;
//import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @description: 数据库连接控制层
 * @author: panChuanJiang
 * @create: 2021-01-12 16:53
 */
@RestController
@Slf4j
@RequestMapping("/dbLink")
public class DbLinkController {
    @Resource
    private DbLinkService dbLinkService;

    @OperationLog("数据连接维护")
    @PostMapping("dbLinkMaintain")
    public APIResult<Object> dbLinkMaintain(@RequestBody DbLinkVo vo) {
        String userId = Optional.ofNullable(String.valueOf(SecurityUtils.getSubject().getPrincipal())).orElse("未知用户");
        vo.setUpdatedBy(userId)
                .setUpdatedDt(DateUtils.getDateString("yyyyMMddHHmmss"));
        dbLinkService.dbLinkMaintain(vo, vo.getOptMode());
        return APIResult.successResult(null);
    }

    @PostMapping("dbLinkQuery")
    public APIResult<PageVo> dbLinkQuery(@RequestBody(required = false) DbLinkVo vo) {
        if (vo != null){
            Integer currentIndex = vo.getCurrentIndex();
            Integer pageSize = vo.getPageSize();
            if (currentIndex != null && pageSize != null && pageSize != 0) {
                int pageNo = currentIndex / pageSize + 1;
                Page<DbLinkPo> page = new Page<>(pageNo, pageSize);
                IPage<DbLinkPo> dbLinks = dbLinkService.selectPageDbLink(page, vo);
                return APIResult.successResult(PageVo.getPageVoFromIPage(dbLinks));
            }
        }
        List<DbLinkPo> dbLinkPos = dbLinkService.selectListDbLink(vo);
        PageVo<DbLinkPo> res = new PageVo<>();
        res.setRecords(dbLinkPos);

        return APIResult.successResult(res);
    }
}
